package ti.me.musicplayer

import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log

class MusicService : Service() {
    companion object {
        const val Command = "operate"
    }
    val TAG = "MusicService"
    val mediaPlayer = MediaPlayer()
    val musicList = mutableListOf<String>()
    val musicNameList = mutableListOf<String>()
    val binder = MusicBinder()
    var current = 0
    var isPause = false

    inner class MusicBinder : Binder() {
            val musicName
                    get()= musicNameList[current]
            var currentPosition
                    get() = mediaPlayer.currentPosition
                    set(value) = mediaPlayer.seekTo(value)
            val duration
                    get() = mediaPlayer.duration
            val size
                    get() = musicList.size
            val currentIndex
                    get() = current
    }

    override fun onCreate() {
        super.onCreate()
        getMusicList()
        mediaPlayer.setOnPreparedListener{
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            current = (current + 1) % musicList.size
            play()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Command, 1)
        when (operate) {
            1 -> play()
            2 -> pause()
            3 -> stop()
            4 -> next()
            5 -> prev()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder {
        return binder
    }


    fun pause(){
        if(isPause){
            mediaPlayer.start()
            isPause = false
        } else {
            mediaPlayer.pause()
            isPause = true
        }
    }

    fun stop(){
        mediaPlayer.stop()
    }

    fun next(){
        current = (current + 1) % musicList.size
        play()
    }

    fun prev(){
        current = (current - 1 + musicList.size) % musicList.size
        play()
    }

    fun play(){
        if (musicList.size == 0) return
        val path = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d(TAG, "play: ${e.message}")
        }
    }

    private fun getMusicList() {
        val cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val musicPath = cursor.getString(cursor.run { getColumnIndex(MediaStore.Audio.Media.DATA) })
                musicList.add(musicPath)
                val musicName = cursor.getString(cursor.run { getColumnIndex(MediaStore.Audio.Media.TITLE) })
                musicNameList.add(musicName)
                Log.d(TAG, "getMusicList: $musicPath name: $musicName")
            }
            cursor.close()
        }
    }
}